package me.zhengjie.spider.util.pipeline;

import cn.hutool.core.collection.CollectionUtil;
import lombok.Data;
import me.zhengjie.spider.common.SpiderConstant;
import me.zhengjie.spider.domain.video.VideoBean;
import me.zhengjie.spider.domain.video.VideoRuleBean;
import me.zhengjie.spider.video.domain.SpiderVideo;
import me.zhengjie.spider.video.service.SpiderVideoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.List;

@Data
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class SpiderVideoDetailPipeline implements Pipeline {

    @Autowired
    private SpiderVideoService spiderVideoService;

    private VideoBean bean;
    private VideoRuleBean ruleBean;

    @Override
    public void process(ResultItems resultItems, Task task) {
        String type = resultItems.get(SpiderConstant.TYPE);
        List<String> tagList = resultItems.get(SpiderConstant.TAG);
        String playLink = resultItems.get(SpiderConstant.PLAY_LINK);
        VideoBean videoBean = getBean();
        videoBean.setType(type);
        if (CollectionUtil.isNotEmpty(tagList)) {
            videoBean.setTag(CollectionUtil.join(CollectionUtil.filter(tagList, tag -> StringUtils.isNotBlank(tag.trim())), SpiderConstant.SEPARATOR));
        }
        if (null != this.ruleBean.getPlayLinkDomain()) {
            playLink = String.format("%s%s", this.ruleBean.getPlayLinkDomain(), playLink);
        }
        videoBean.setPlayLink(playLink);
        SpiderVideo spiderVideo = new SpiderVideo();
        BeanUtils.copyProperties(videoBean, spiderVideo);
        spiderVideo.setDeletedFlag(false);
        this.spiderVideoService.update(spiderVideo);
    }
}
